package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.RedisData;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import io.lettuce.core.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisAccessor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private CacheClient cacheClient;
    @Override
    public Result queryById(Long id) {
        //缓存穿透
        //Shop shop = queryWithPassThrough(id);
        Shop shop = cacheClient.queryWithMLogicalExpire(RedisConstants.CACHE_SHOP_KEY,id,Shop.class,
                RedisConstants.LOCK_SHOP_KEY,RedisConstants.LOCK_SHOP_TTL,this::getById,RedisConstants.CACHE_SHOP_TTL,TimeUnit.SECONDS);
        //用逻辑过期解决缓存穿透
//        Shop shop = queryWithMLogicalExpire(id);
        if (shop == null) {
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }

    /*public Shop queryWithPassThrough(Long id) {
        String key=RedisConstants.CACHE_SHOP_KEY + id;
        //先查缓存
        String cacheShopJSON = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(cacheShopJSON)) {
            Shop shop = JSONUtil.toBean(cacheShopJSON, Shop.class);
            return shop;
        }
        if (cacheShopJSON != null) {
            return null;
        }
        //再查数据库
        Shop shop = getById(id);
        if (shop == null) {
            stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //写入redis
        stringRedisTemplate.opsForValue()
                .set(key, JSONUtil.toJsonStr(shop),RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop;
    }*/

    //商铺缓存重建的线程池
    private static final ExecutorService CACHE_REBUIDER_EXCUTOR = Executors.newFixedThreadPool(10);

    public Shop queryWithMLogicalExpire(Long id) {
        String key=RedisConstants.CACHE_SHOP_KEY + id;
        //先查缓存
        String cacheShopJSON = stringRedisTemplate.opsForValue().get(key);
        //未命中，直接返回空
        //因为此时已经进行数据预热，把数据库中的数据预先存进了redis中
        //所以说cacheShopJSON为null时，不需要再查数据库
        if (StrUtil.isBlank(cacheShopJSON)) {
            return null;
        }
        //拿出封装的数据和逻辑过期时间，反序列化成对象
        RedisData redisData = JSONUtil.toBean(cacheShopJSON, RedisData.class);
        //
        Shop cacheShop = JSONUtil.toBean((JSONObject)redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        //判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //未过期则直接返回数据
            return cacheShop;
        }
        //过期，则尝试获取锁
        String lockShopKey = RedisConstants.LOCK_SHOP_KEY;
        boolean isLock = tryLock(lockShopKey);
        //获取成功，尝试重建缓存，开启新线程，更新过期时间
        if (isLock) {
            CACHE_REBUIDER_EXCUTOR.submit(()->{
                try {
                    this.saveShop2Redis(id,10L);
                    log.info("缓存重建了");
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unlock(lockShopKey);
                }
            });
        }
        //返回过期数据
        return cacheShop;
    }

    public void saveShop2Redis(Long id, Long expireSeconds) {
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        Shop shop = getById(id);
        //模拟延迟
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        String redisDataJsonStr = JSONUtil.toJsonStr(redisData);
        //写入redis
        stringRedisTemplate.opsForValue().set(key,redisDataJsonStr);
    }

    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue()
                .setIfAbsent(key, "1", RedisConstants.LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateShopById(Shop shop) {
        //先更新数据库再更新缓存，保持高度一致性
        Long id = shop.getId();
        updateById(shop);
        //更新缓存
        String key=RedisConstants.CACHE_SHOP_KEY + id;
        stringRedisTemplate.delete(key);
        return Result.ok();
    }
}
